package com.ssm.demo.Util;

import com.sun.org.apache.xml.internal.security.utils.Base64;

import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.*;

public class Crypt {

    public static String encode(String key,String iv,String data){
        try {
            com.sun.org.apache.xml.internal.security.Init.init();
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            Key skey = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec param = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.ENCRYPT_MODE, skey, param);
            return Base64.encode(cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String decode(String key,String iv,String data){
        try {
            com.sun.org.apache.xml.internal.security.Init.init();
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            Key skey = new SecretKeySpec(key.getBytes(), "AES");
            IvParameterSpec param = new IvParameterSpec(iv.getBytes());
            cipher.init(Cipher.DECRYPT_MODE, skey, param);
            return new String(cipher.doFinal(Base64.decode(data)));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String args[]){
        String str = encode("dfcbim_a12345678","361457cc34311c44","我们一起");
        System.out.println(str);
        str = decode("dfcbim_a12345678","361457cc34311c44",str );
        System.out.println(str);
    }

}
